import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import Layout from './Layout';
import './Orders.css';

interface OrderItem {
    id: string;
    name: string;
    price: number;
    quantity: number;
    image: string;
    selectedSpecs: {
        color?: string;
        storage?: string;
    };
    selectedServices: string[];
    selectedAccessories: string[];
}

interface Order {
    id: string;
    items: OrderItem[];
    address: {
        name: string;
        phone: string;
        province: string;
        city: string;
        district: string;
        detail: string;
    };
    total: number;
    status: string;
    createTime: string;
}

const Orders = () => {
    const navigate = useNavigate();
    const [orders, setOrders] = useState<Order[]>([]);
    const [activeTab, setActiveTab] = useState('all');
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        try {
            const storedOrders = JSON.parse(sessionStorage.getItem('orders') || '[]');
            setOrders(storedOrders || []);
        } catch (err) {
            setError('加载订单数据失败');
            console.error('Error loading orders:', err);
            setOrders([]);
        } finally {
            setLoading(false);
        }
    }, []);

    const formatDate = useCallback((dateString: string) => {
        try {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        } catch (err) {
            console.error('Error formatting date:', err);
            return dateString;
        }
    }, []);

    const getStatusText = useCallback((status: string) => {
        const statusMap: { [key: string]: string } = {
            '待付款': '待付款',
            '待发货': '待发货',
            '待收货': '待收货',
            '已完成': '已完成',
            '已取消': '已取消'
        };
        return statusMap[status] || status;
    }, []);

    const getStatusClass = useCallback((status: string) => {
        const classMap: { [key: string]: string } = {
            '待付款': 'status-pending',
            '待发货': 'status-processing',
            '待收货': 'status-shipping',
            '已完成': 'status-completed',
            '已取消': 'status-cancelled'
        };
        return classMap[status] || '';
    }, []);

    const filteredOrders = useMemo(() => {
        if (!orders) return [];
        return orders.filter(order => {
            if (activeTab === 'all') return true;
            return order.status === activeTab;
        });
    }, [orders, activeTab]);

    const handleViewOrderDetail = useCallback((orderId: string) => {
        navigate(`/order-detail/${orderId}`);
    }, [navigate]);

    const handleTabChange = useCallback((tab: string) => {
        setActiveTab(tab);
    }, []);

    if (loading) {
        return <div className="loading">加载中...</div>;
    }

    if (error) {
        return <div className="error">{error}</div>;
    }

    return (
        <Layout>
            <div className="orders-page">
                <div className="orders-header">
                    <h2>我的订单</h2>
                    <div className="order-tabs">
                        {['all', '待付款', '待发货', '待收货', '已完成'].map(tab => (
                            <button
                                key={tab}
                                className={`tab ${activeTab === tab ? 'active' : ''}`}
                                onClick={() => handleTabChange(tab)}
                            >
                                {tab === 'all' ? '全部订单' : tab}
                            </button>
                        ))}
                    </div>
                </div>

                <div className="orders-list">
                    {(!filteredOrders || filteredOrders.length === 0) ? (
                        <div className="empty-orders">
                            <img src="../imgs/订单空.png" alt="暂无订单" />
                            <p>暂无订单</p>
                            <button onClick={() => navigate('/productDetail')}>去购物</button>
                        </div>
                    ) : (
                        filteredOrders.map(order => (
                            <div key={order.id} className="order-card">
                                <div className="order-header">
                                    <div className="order-info">
                                        <span className="order-time">{formatDate(order.createTime)}</span>
                                        <span className="order-number">订单号：{order.id}</span>
                                    </div>
                                    <span className={`order-status ${getStatusClass(order.status)}`}>
                                        {getStatusText(order.status)}
                                    </span>
                                </div>

                                <div className="order-items">
                                    {order.items && order.items.map((item: OrderItem) => (
                                        <div key={item.id} className="order-item">
                                            <img src='https://res2.vmallres.com/pimages/FssCdnProxy/vmall_product_uom/pmsSalesFile/428_428_D0C8A9A011D150F59C4108C3AF625E3C.png' alt={item.name} className="item-image" />
                                            <div className="item-info">
                                                <h4>{item.name}</h4>
                                                <p className="specs">
                                                    {item.selectedSpecs.color && `颜色：${item.selectedSpecs.color}`}
                                                    {item.selectedSpecs.storage && ` 存储：${item.selectedSpecs.storage}`}
                                                </p>
                                                <div className="services">
                                                    {item.selectedServices && item.selectedServices.map((serviceId: string) => (
                                                        <span key={serviceId} className="service-tag">
                                                            {serviceId}
                                                        </span>
                                                    ))}
                                                </div>
                                                <div className="accessories">
                                                    {item.selectedAccessories && item.selectedAccessories.map((accessoryId: string) => (
                                                        <span key={accessoryId} className="accessory-tag">
                                                            {accessoryId}
                                                        </span>
                                                    ))}
                                                </div>
                                            </div>
                                            <div className="item-price">¥{item.price}</div>
                                            <div className="item-quantity">x{item.quantity}</div>
                                        </div>
                                    ))}
                                </div>

                                <div className="order-footer">
                                    <div className="order-total">
                                        共{order.items ? order.items.reduce((sum, item) => sum + item.quantity, 0) : 0}件商品
                                        合计：<span className="total-amount">¥{order.total}</span>
                                    </div>
                                    <div className="order-actions">
                                        {order.status === '待付款' && (
                                            <button className="pay-button" onClick={() => navigate('/payment')}>
                                                立即付款
                                            </button>
                                        )}
                                        {order.status === '待收货' && (
                                            <button className="confirm-button">
                                                确认收货
                                            </button>
                                        )}
                                        {order.status === '已完成' && (
                                            <button className="review-button">
                                                评价
                                            </button>
                                        )}
                                        <button className="detail-button" onClick={() => handleViewOrderDetail(order.id)}>
                                            订单详情
                                        </button>
                                    </div>
                                </div>
                            </div>
                        ))
                    )}
                </div>
            </div>
        </Layout>
    );
};

export default Orders; 